package com.cloudcc.mobile.view.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.cloudcc.cloudframe.bus.EventEngine;
import com.cloudcc.cloudframe.bus.IEventLife;
import com.cloudcc.cloudframe.util.DensityUtils;
import com.cloudcc.mobile.AppContext;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.adapter.AtNewContaxtAdapter;
import com.cloudcc.mobile.dialog.CallLogLoadingDialog;
import com.cloudcc.mobile.entity.CoworkerEntity;
import com.cloudcc.mobile.entity.User;
import com.cloudcc.mobile.event.CoworkerEventList;
import com.cloudcc.mobile.event.CustomerEventList;
import com.cloudcc.mobile.manager.RunTimeManager;
import com.cloudcc.mobile.manager.UserManager;
import com.cloudcc.mobile.parser.UserParser;
import com.cloudcc.mobile.presenter.ContactsPresenter;
import com.cloudcc.mobile.service.UserService;
import com.cloudcc.mobile.util.AsyncTaskBase;
import com.cloudcc.mobile.util.CharacterParser;
import com.cloudcc.mobile.util.PinyinComparator;
import com.cloudcc.mobile.util.PinyinUtils;
import com.cloudcc.mobile.util.Tools;
import com.cloudcc.mobile.view.base.BaseActivity;
import com.cloudcc.mobile.weight.ClearEditText;
import com.cloudcc.mobile.weight.CustomListView;
import com.cloudcc.mobile.weight.CustomListView.OnRefreshListener;
import com.cloudcc.mobile.weight.LoadingView;
import com.cloudcc.mobile.weight.SideBar;
import com.cloudcc.mobile.weight.SideBar.OnTouchingLetterChangedListener;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.exception.DbException;

import org.w3c.dom.Text;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @某人的activity
 * @author Administrator
 * 
 */
public class AtContaxtActivity extends BaseActivity implements IEventLife {
	private String mEns = RunTimeManager.getInstance().getlanguage();
	private CustomListView sortListView;
	private SideBar sideBar;
	private TextView dialog, title;
	private TextView finish;
	private ClearEditText mClearEditText;
	private Map<String, User> callRecords;
	private LoadingView mLoadingView;
	private AtNewContaxtAdapter adapter;
	private ImageView set;
	private StringBuilder sb = new StringBuilder();

	/**
	 * 汉字转换成拼音的类
	 */
	private CharacterParser characterParser;
	private List<CoworkerEntity> SourceDateList;

	/**
	 * 根据拼音来排列ListView里面的数据类
	 */
	private PinyinComparator pinyinComparator;
	private LinearLayout contaxt_bg;
	private float ux, dx;
	private TextView no_contaxt;
	private ImageView no_network;
	private FrameLayout frame;
	private ContactsPresenter presenter;

	CallLogLoadingDialog callLogLoadingDialogx ;

	@Override
	public int getLayoutId() {
		return R.layout.chat_contaxt3;
	}

	@Override
	public void init(Bundle savedInstanceState) {
		super.init(savedInstanceState);
		presenter = new ContactsPresenter();
		register();
		setupView();
		initData();
		addListener();
	}

	/**
	 * 滑动返回
	 */

	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		// 当按下时处理
		if (ev.getAction() == MotionEvent.ACTION_DOWN) {
			dx = ev.getX();
		} else if (ev.getAction() == MotionEvent.ACTION_UP) {// 松开处理
			ux = ev.getX();
			if ((int) (ux - dx) > DensityUtils.getScreenWidth(mContext) / 2
					&& ux > dx) {
				finish();
				// 设置切换动画，从右边进入，左边退出
				overridePendingTransition(R.anim.in_from_left,
						R.anim.out_to_right);
			}
		}
		return super.dispatchTouchEvent(ev);
	}

	@Override
	protected void onDestroy() {
		unRegister();
		try {
			AppContext.getInstance().contactmap.clear();
			super.onDestroy();
		} catch (Exception e) {
			Tools.handle(e);
		}
	}

	private void addListener() {
		// 根据输入框输入值的改变来过滤搜索
		mClearEditText.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// 当输入框里面的值为空，更新为原来的列表，否则为过滤数据列表
				filterData(s.toString());
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
			}
		});
		finish.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent();
				intent.putExtra("name", sb.toString());
				setResult(RESULT_OK, intent);
				AtContaxtActivity.this.finish();
			}
		});
		/**
		 * 点击刷新
		 */
		frame.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
//				mLoadingView.setVisibility(View.VISIBLE);
				showDialogTy(getString(R.string.loading));
				frame.setVisibility(View.GONE);
//				new AsyncTaskConstact(mLoadingView).execute(0);
				presenter.getContactListNew(null);

			}
		});
		// listview 做监听
		sortListView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				String name = adapter.getItem(arg2 - 1).getName();
				char[] cc = sb.toString().toCharArray();
				int total = 0;
				for (int i = 0; i < cc.length; i++) {
					if (cc[i] == ',') {
						total++;
					}
				}
				String[] c = sb.toString().split(",");
				if (total <= 10) {
					boolean a = false;
					ArrayList<String> p = new ArrayList<String>();
					for (int j = 0; j < c.length; j++) {
						p.add(c[j]);
						if (name.equals((c[j]))) {
							a = true;
							p.remove(j);
						}
					}
					if (!a) {
						sb.append(name).append(",");
					} else {
						sb = new StringBuilder();
						for (int k = 0; k < p.size(); k++) {
							sb.append(p.get(k)).append(",");
						}
					}
					if (AppContext.getInstance().contactmap
							.containsKey(arg2 - 1)) {
						AppContext.getInstance().contactmap.remove(arg2 - 1);
					} else {
						AppContext.getInstance().contactmap.put(arg2 - 1, 200);
					}
					adapter.notifyDataSetChanged();
				} else {
					if ("en".equals(mEns)) {
						Tools.showInfo(AtContaxtActivity.this, "Pro - up to 10 people");
					}else{
						Tools.showInfo(AtContaxtActivity.this, "亲~ 最多能@10个人");
				}
					
				}

			}
		});
		set.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				AtContaxtActivity.this.finish();
			}
		});

		// 设置右侧触摸监听
		sideBar.setOnTouchingLetterChangedListener(new OnTouchingLetterChangedListener() {
			@SuppressLint("NewApi")
			@Override
			public void onTouchingLetterChanged(String s) {
				// 该字母首次出现的位置
				int position = adapter.getPositionForSection(s.charAt(0));
				if (position != -1) {
					sortListView.setSelection(position);
				}
			}
		});
		/**
		 * 下拉刷新
		 */
		sortListView.setOnRefreshListener(new OnRefreshListener() {
			@Override
			public void onRefresh() {
				showDialogTy(getString(R.string.loading));
//				new AsyncTaskConstact(mLoadingView).execute(0);
				presenter.getContactListNew(null);
			}
		});
	}

	private void setupView() {
		frame = (FrameLayout) findViewById(R.id.frame);
		title = (TextView) findViewById(R.id.title);
		if ("en".equals(mEns)) {
			title.setText("Choose Colleague");
		}else{
			title.setText("选择@同事");
	}
		finish = (TextView) findViewById(R.id.finish);
		set = (ImageView) findViewById(R.id.chatcontact_menubtn);
		set.setImageResource(R.drawable.fujin_back);
		no_contaxt = (TextView) findViewById(R.id.empty_contaxt);
		no_network = (ImageView) findViewById(R.id.contaxt_no_work);
		contaxt_bg = (LinearLayout) findViewById(R.id.contaxt_bg);
		mLoadingView = (LoadingView) findViewById(R.id.contactloading);
		sideBar = (SideBar) findViewById(R.id.sidrbar);
		dialog = (TextView) findViewById(R.id.dialog);
		sortListView = (CustomListView) findViewById(R.id.chat_contaxt_list);
		mClearEditText = (ClearEditText) findViewById(R.id.filter_edit);
		// 实例化汉字转拼音类
		characterParser = CharacterParser.getInstance();
		pinyinComparator = new PinyinComparator();
		SourceDateList = new ArrayList<CoworkerEntity>();
		DbUtils db = DbUtils.create(this,
				UserManager.getManager().getUser().userId + "chat");
		try {
			if (db.tableIsExist(CoworkerEntity.class)) {
				SourceDateList = db.findAll(CoworkerEntity.class);
				// 根据a-z进行排序源数据
				Collections.sort(SourceDateList, pinyinComparator);
				adapter = new AtNewContaxtAdapter(this, SourceDateList);
				sortListView.setAdapter(adapter);
				// 获取审批人id
				// Log.d("SourceDateList", SourceDateList.get(0).getId()+"这个是");
				contaxt_bg.setVisibility(View.VISIBLE);
			} else {
				adapter = new AtNewContaxtAdapter(this, SourceDateList);
				// Log.d("SourceDateList", SourceDateList.get(0).getId()+"这个是");
				sortListView.setAdapter(adapter);
			}
		} catch (DbException e) {
			Tools.handle(e);
		}
	}

	private void noData() {
		if (SourceDateList.size() == 0) {
			frame.setVisibility(View.VISIBLE);
			no_contaxt.setVisibility(View.VISIBLE);
			no_network.setVisibility(View.GONE);
			contaxt_bg.setVisibility(View.GONE);
		}
	}

	private void noNetWork() {
		if (SourceDateList.size() == 0) {
			frame.setVisibility(View.VISIBLE);
			no_contaxt.setVisibility(View.GONE);
			no_network.setVisibility(View.VISIBLE);
			contaxt_bg.setVisibility(View.GONE);
		}
	}

	private void initData() {
		sideBar.setTextView(dialog);
		showDialogTy(getString(R.string.loading));
//		new AsyncTaskConstact(mLoadingView).execute(0);
		presenter.getContactListNew(null);
	}

	protected void showDialogTy(String text){
		callLogLoadingDialogx = new CallLogLoadingDialog(this,R.style.DialogLoadingTheme);
		callLogLoadingDialogx.show();
		callLogLoadingDialogx.settext(text);
	}

	/**
	 * 取消 显示等待的dialog
	 */
	protected void dismissWainting() {
		if (callLogLoadingDialogx != null) {
			callLogLoadingDialogx.dismiss();
			callLogLoadingDialogx = null;
		}
	}

	@Override
	public void register() {
		EventEngine.register(this);
	}

	@Override
	public void unRegister() {
		EventEngine.uregister(this);
	}

	public void onEventMainThread(CoworkerEventList.CoworkerListEvent event) {
		if(event == null && event.isError()){
			dismissWainting();
			mLoadingView.setVisibility(View.GONE);
			sortListView.setCanRefresh(true);
			noNetWork();
			sortListView.onRefreshComplete(); // 下拉刷新完成
		}else {
			SourceDateList = event.getData();
			filledData();
			DbUtils db = DbUtils.create(mContext, UserManager
					.getManager().getUser().userId + "chat");
			try {
				if (db.tableIsExist(CoworkerEntity.class)) {
					db.deleteAll(CoworkerEntity.class);
				}
				db.saveAll(SourceDateList);
			} catch (DbException e) {
				Tools.handle(e);
			}
			// 根据a-z进行排序源数据
			Collections.sort(SourceDateList, pinyinComparator);
			handler.sendEmptyMessage(2);
		}
	}

//	private class AsyncTaskConstact extends AsyncTaskBase {
//
//		public AsyncTaskConstact(LoadingView loadingView) {
//			super(loadingView);
//		}
//
//		@Override
//		protected Integer doInBackground(Integer... params) {
//			int result = -1;
//			UserService service = new UserService();
//			String jsonString = service.getUsers("");
//			if (Tools.isNull(jsonString)) {
//				return 0;
//			} else if (jsonString.equals("outTime")) {
//				return 2;// 超时
//			} else if (jsonString.equals("NetworkError")) {
//				return 3;// 网络异常
//			}
//
//			// callRecords = ConstactUtil.getAllCallRecords(mContext);
//			callRecords = UserParser.getAllCallRecords(mContext, jsonString);
//			if (callRecords == null) {
//				return 0;
//			}
//			result = 1;
//			return result;
//		}
//
//		@Override
//		protected void onPostExecute(final Integer result) {
//			super.onPostExecute(result);
//			String s = "查询异常";
//			if ("en".equals(mEns)) {
//				s = "Query exception";
//			}else{
//			s = "查询异常";
//		}
//			if (result == 0) {
//				dismissWainting();
//				mLoadingView.setVisibility(View.GONE);
//				Tools.showInfo(mContext, s);
//				noNetWork();
//				sortListView.setCanRefresh(true);
//				sortListView.onRefreshComplete(); // 下拉刷新完成
//				return;
//			} else if (result == 2) {
//				dismissWainting();
//				mLoadingView.setVisibility(View.GONE);
//				Tools.showInfo(mContext, s);
//				sortListView.setCanRefresh(true);
//				noNetWork();
//				sortListView.onRefreshComplete(); // 下拉刷新完成
//				return;
//			} else if (result == 3) {
//				dismissWainting();
//				mLoadingView.setVisibility(View.GONE);
//				Tools.showInfo(mContext, s);
//				noNetWork();
//				sortListView.setCanRefresh(true);
//				sortListView.onRefreshComplete(); // 下拉刷新完成
//				return;
//			}
//
//			new Thread() {
//				public void run() {
//					if (result == 1) {
//						List<String> constact = new ArrayList<String>();
//						for (Iterator<String> keys = callRecords.keySet()
//								.iterator(); keys.hasNext();) {
//							String key = keys.next();
//							constact.add(key);
//						}
//						String[] names = new String[] {};
//						names = constact.toArray(names);
//						SourceDateList = filledData(names);
//						DbUtils db = DbUtils.create(mContext, UserManager
//								.getManager().getUser().userId + "chat");
//						try {
//							if (db.tableIsExist(CoworkerEntity.class)) {
//								db.deleteAll(CoworkerEntity.class);
//							}
//							db.saveAll(SourceDateList);
//						} catch (DbException e) {
//							Tools.handle(e);
//						}
//						// 根据a-z进行排序源数据
//						Collections.sort(SourceDateList, pinyinComparator);
//						handler.sendEmptyMessage(2);
//					}
//				}
//			}.start();
//
//		}
//	}

	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 2:
				adapter.updateListView(SourceDateList);
				sortListView.setAdapter(adapter);
				contaxt_bg.setVisibility(View.VISIBLE);
				frame.setVisibility(View.GONE);
				dismissWainting();
				mLoadingView.setVisibility(View.GONE);
				sortListView.setCanRefresh(true);
				adapter.notifyDataSetChanged();
				sortListView.onRefreshComplete(); // 下拉刷新完成
				noData();
				break;
			default:
				break;
			}
			super.handleMessage(msg);
		}
	};

	private void filledData() {

		for (int i = 0; i < SourceDateList.size(); i++) {
			String names = SourceDateList.get(i).getName();
			// 汉字转换成拼音
			// String pinyin = characterParser.getSelling(date[i]);
			if (names.trim().equals("") || names.trim().equals("null")) {
				continue;
			}
			String pinyin = PinyinUtils.getPingYin(names);
			String sortString = pinyin.substring(0, 1).toUpperCase();
			// String sortString=PinyinUtils.cn2FirstSpell(date[i]);
			// 正则表达式，判断首字母是否是英文字母
			if (sortString.matches("[A-Z]")) {
				SourceDateList.get(i).setSortLetters(sortString.toUpperCase());
			} else {
				SourceDateList.get(i).setSortLetters("#");
			}
		}

	}

	/**
	 * 根据输入框中的值来过滤数据并更新ListView
	 * 
	 * @param filterStr
	 */
	private void filterData(String filterStr) {
		List<CoworkerEntity> filterDateList = new ArrayList<CoworkerEntity>();
		if (TextUtils.isEmpty(filterStr)) {
			filterDateList = SourceDateList;
		} else {
			filterDateList.clear();
			for (CoworkerEntity sortModel : SourceDateList) {
				String name = sortModel.getName();
				if (name.indexOf(filterStr.toString()) != -1
						|| characterParser.getSelling(name).startsWith(
								filterStr.toString())) {
					filterDateList.add(sortModel);
				}
			}
		}

		// 根据a-z进行排序
		Collections.sort(filterDateList, pinyinComparator);
		adapter.updateListView(filterDateList);
	}

}
